﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SCRendererNV12 : SCCanvas {

    private Material mat;
    private byte[] cacheY, cacheUV;
    public SCRendererNV12(OutPixFmt fmt)
    {
        texs = new Texture2D[2];
    }

    public override void InitCanvas(ref Material mat, VideoStream vs)
    {
        base.InitCanvas(ref mat, vs);
        this.mat = mat = new Material(Resources.Load<Material>("StreamCapture/SCMatNV12"));
        texs[0] = new Texture2D(width, height, TextureFormat.R8, false);
        texs[1] = new Texture2D(width / 2, height / 2, TextureFormat.RG16, false);
    }

    public override void Renderer(Frame frame)
    {

        if (frame == null) return;

        if (frame.format != (int)OutPixFmt.PIX_FMT_NV12)
        {
            Debug.LogError("The pixel format is different from the canvas type");
            return;
        }

        if (frame.linesize[0] != width || frame.linesize[1] != width)
        {
            if (cacheY == null)
            {
                cacheY = new byte[width * height];
            }
            if(cacheUV == null)
            {
                cacheUV = new byte[width * height / 2];
            }
            frame.data[0] = IStreamCapture.MemoryAlignment(frame.data[0], width, height, frame.linesize[0], cacheY);
            frame.data[1] = IStreamCapture.MemoryAlignment(frame.data[1], width, height, frame.linesize[1], cacheY);
        }

        texs[0].LoadRawTextureData(frame.data[0], width * height);
        texs[1].LoadRawTextureData(frame.data[1], width * height);


        texs[0].Apply();
        texs[1].Apply();


        mat.SetTexture("_YTex", texs[0]);
        mat.SetTexture("_UVTex", texs[1]);
    }
}
